#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include "unistd.h"
#include "Task.hpp"
#include "ThreadPool.hpp"
#include "log.hpp"

using namespace std;

namespace server
{
    enum
    {
        USAGE_ERR = 1,
        SOCK_ERR,
        BIND_ERR,
        LISTEN_ERR
    };
    static const uint16_t gport = 8080;
    static const int gbacklog = 5; // 大于0，小于20，一般来说

    class TcpServer;
    class ThreadData
    {
    public:
        ThreadData(TcpServer *self, int sock) : _self(self), _sock(sock)
        {
        }
        ~ThreadData()
        {
        }

    public:
        TcpServer *_self;
        int _sock;
    };
    class TcpServer
    {
    public:
        TcpServer(uint16_t port = gport) : _listensock(-1), _port(port)
        {
        }
        void initServer()
        {
            // 1.创建套接字
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                logMessage(FATAL, "creat socket error");
                exit(SOCK_ERR);
            }
            logMessage(NOMAL, "creat socket success");

            // 2.bind自己的网络信息
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;
            if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                logMessage(FATAL, "bind socket error");
                exit(BIND_ERR);
            }
            logMessage(NOMAL, "bind socket success");

            // 3.设置sock为listen监听状态
            if (listen(_listensock, gbacklog) < 0)
            {
                logMessage(FATAL, "listen socket error");
                exit(LISTEN_ERR);
            }
            logMessage(NOMAL, "listen socket success:%d", _listensock);
        }
        void start()
        {
            // 4.线程池初始化
            ThreadPool<Task>::getInstance()->run();
            for (;;)
            {
                // 1.server获取新连接
                // sock,和client进行通信的fd
                struct sockaddr_in peer;
                socklen_t peerlen = sizeof(peer);
                int sock = accept(_listensock, (struct sockaddr *)&peer, &peerlen);
                if (sock < 0)
                {
                    logMessage(ERROR, "accept error,next");
                    continue;
                }
                logMessage(NOMAL, "accept new link success");
                logMessage(ERROR, "accept error,next");
                logMessage(FATAL, "accept error,next");
                logMessage(DEBUG, "accept error,next");
                logMessage(WARING, "accept error,next");

                logMessage(NOMAL, "accept new link success");
                logMessage(ERROR, "accept error,next");
                logMessage(FATAL, "accept error,next");
                logMessage(DEBUG, "accept error,next");
                logMessage(WARING, "accept error,next");

                logMessage(NOMAL, "accept new link success");
                logMessage(ERROR, "accept error,next");
                logMessage(FATAL, "accept error,next");
                logMessage(DEBUG, "accept error,next");
                logMessage(WARING, "accept error,next");
                // 5.这里是一个sock，未来通信我们就用这个sock，面向字节流的，猴戏全部都是文件操作！

                // version 1
                /*serverIO(sock);
                close(sock);// 对于一个已经使用完毕的sock，要关闭这个sock，不然会导致，文件描述符泄露！*/

                // version 2 多进程版
                /*pid_t id = fork();
                if(id == 0)// child
                {
                    close(_listensock);// 最好关闭，不要出现误操作
                    if(fork() > 0) exit(0);// 下面就是孤儿进程
                    serverIO(sock);
                    close(sock);
                    exit(0);
                }
                close(sock);
                // father
                pid_t ret = waitpid(id,nullptr,0);
                if(ret > 0)
                {
                    cout << "waitpid success: " << ret << endl;
                }*/

                // version 3多线程版
                /*pthread_t tid;
                ThreadData* td = new ThreadData(this,sock);
                pthread_create(&tid,nullptr,threadRoutine,td);*/
                // pthread_join(tid,nullptr);

                // version 4线程池版
                ThreadPool<Task>::getInstance()->push(Task(sock, serverIO));
            }
        }

        // static void *threadRoutine(void *args)
        // {
        //     ThreadData *td = static_cast<ThreadData *>(args);

        //     td->_self->serverIO(td->_sock);
        //     delete td;
        //     close(td->_sock);
        //     return nullptr;
        // }

        ~TcpServer()
        {
        }

    private:
        int _listensock;
        uint16_t _port;
    };
}